<template>
    <button @click.once="addSubject">添加课程（数组最前面）</button>

    <h3>不使用key值</h3>
    <ul>
        <li v-for="sub in subject">
            <input type="checkbox">
            {{ sub }}
        </li>
    </ul>

    <hr>
    <h3>使用索引当key值</h3>
    <ul>
        <li v-for="(sub, index) in subject" :key="index">
            <input type="checkbox">
            {{ sub }}
        </li>
    </ul>

    <hr>
    <h3>使用列表属性当key值（该属性必须再此列表中唯一）</h3>
    <ul>
        <li v-for="sub in subject" :key="sub.id">
            <input type="checkbox">
            {{ sub }}
        </li>
    </ul>
</template>

<script setup>
import {ref} from 'vue'

let subject = ref([ // 课程
    {id: 1, name: 'Vue'},
    {id: 2, name: 'Java'},
    {id: 3, name: 'Hadoop'}
])

function addSubject() { // 添加课程
    subject.value.unshift({id: 4, name: 'Python'}) // （数组最前面）添加
}
</script>

<script>
export default {
    data: () => ({
        subject: [
            {id: 1, name: 'Vue'},
            {id: 2, name: 'Java'},
            {id: 3, name: 'Hadoop'}
        ]
    }),
    methods: {
        addSubject() { // 添加课程
            this.subject.unshift({id: 4, name: 'Python'})  // （数组最前面）添加
        }
    }
}
</script>